{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "c:\\Users\\www\\Desktop\\lijingqi\n",
      "题库管理系统\n",
      "1. 查看题目索引\n",
      "2. 运行题目\n",
      "3. 增加题目\n",
      "4. 使用 subprocess 执行外部程序\n",
      "5. 退出\n",
      "题目索引:\n",
      "1. 1.输入某年某月某日，判断这一天是这一年的第几天？\n",
      "2. 2.判断1000中有多少个素数,并输出所有素数。\n",
      "3. 3.利用条件运算符的嵌套来完成此题：学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。(要求有键盘输入)。\n",
      "4. 4.输入一行字符串，分别统计出其中英文字母、空格、数字和其它字符的个数。\n",
      "5. 5.一个数如果恰好等于它的因子之和,这个数就称为“完数”。例如6=1+2+3.编程,找出1000以内的所有完数。\n",
      "6. 6.输入任意数N,求1+2!+3!+...+N!的值（注意实数范围）\n",
      "7. 7.对10个数进行排序。\n",
      "8. 8.有一个已经排好序的数组(元素数量大于10)。从键盘任意输入一个数，要求按原来的规律将它插入数组中。\n",
      "9. 9.有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。\n",
      "题库管理系统\n",
      "1. 查看题目索引\n",
      "2. 运行题目\n",
      "3. 增加题目\n",
      "4. 使用 subprocess 执行外部程序\n",
      "5. 退出\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import importlib.util\n",
    "import subprocess\n",
    "import sys\n",
    "from datetime import datetime  # 将datetime导入放在顶部\n",
    "\n",
    "# 题目库目录\n",
    "QUESTION_DIR = 'questions'\n",
    "print(os.getcwd())\n",
    "\n",
    "# 初始化题库（这里只是一个简单的字典模拟）\n",
    "question_bank ={\n",
    "    1: \"1.输入某年某月某日，判断这一天是这一年的第几天？\",\n",
    "    2: \"2.判断1000中有多少个素数,并输出所有素数。\",\n",
    "    3: \"3.利用条件运算符的嵌套来完成此题：学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。(要求有键盘输入)。\",\n",
    "    4: \"4.输入一行字符串，分别统计出其中英文字母、空格、数字和其它字符的个数。\",\n",
    "    5: \"5.一个数如果恰好等于它的因子之和,这个数就称为“完数”。例如6=1+2+3.编程,找出1000以内的所有完数。\",\n",
    "    6:\"6.输入任意数N,求1+2!+3!+...+N!的值（注意实数范围）\",\n",
    "    7:\"7.对10个数进行排序。\",\n",
    "    8:\"8.有一个已经排好序的数组(元素数量大于10)。从键盘任意输入一个数，要求按原来的规律将它插入数组中。\",\n",
    "    9:\"9.有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。\"\n",
    "    }\n",
    "    # 其他题目可以手动添加或通过程序添加\n",
    "\n",
    "\n",
    "# 初始化题目文件路径\n",
    "def init_question_files():\n",
    "    if not os.path.exists(QUESTION_DIR):\n",
    "        os.makedirs(QUESTION_DIR)\n",
    "  # 为特定题目编号生成solve函数文件（新函数）\n",
    "def generate_solve_file(question_number, description):\n",
    "    file_path = os.path.join(QUESTION_DIR, f\"question_{question_number}.py\")\n",
    "    # 根据题目编号生成不同的solve函数内容\n",
    "    if question_number == 1:\n",
    "        content = f\"\"\"# 题目 {question_number}: {description}\n",
    "def solve():\n",
    "    year, month, day = map(int, input(\"请输入年月日（用空格分隔）: \").split())\n",
    "    date = datetime(year, month, day)\n",
    "    start_of_year = datetime(year, 1, 1)\n",
    "    delta = date - start_of_year\n",
    "    return f\"{{date}} 是这一年的第 {{delta.days + 1}} 天\"\n",
    "\"\"\"\n",
    "    if question_number == 2:\n",
    "        content = f\"\"\"# 题目 {question_number}: {description}\n",
    "def solve():\n",
    "    def is_prime(n):\n",
    "        if n <= 1:\n",
    "            return False\n",
    "        for i in range(2, int(n**0.5) + 1):\n",
    "            if n % i == 0:\n",
    "                return False\n",
    "        return True\n",
    " \n",
    "    primes = [i for i in range(2, 1001) if is_prime(i)]\n",
    "    return f\"1000以内的素数共有 {{len(primes)}} 个，分别是: {{primes}}\"\n",
    "\"\"\"\n",
    "    if question_number == 3:\n",
    "        content = f\"\"\"# 题目 {question_number}: {description}\n",
    "def solve():\n",
    "     score = float(input(\"请输入学习成绩: \"))\n",
    "    grade = 'A' if score >= 90 else ('B' if 60 <= score < 90 else 'C')\n",
    "    return f\"学习成绩 {'score'} 对应的等级是 {'grade'}\"\n",
    " \"\"\"     \n",
    "    if question_number == 4:\n",
    "        content = f\"\"\"# 题目 {question_number}: {description}\n",
    "def solve():\n",
    "    text = input(\"请输入一行字符串: \")\n",
    "    letters = sum(1 for c in text if c.isalpha())\n",
    "    spaces = text.count(' ')\n",
    "    digits = sum(1 for c in text if c.isdigit())\n",
    "    others = len(text) - letters - spaces - digits\n",
    "    return f\"英文字母: {'letters'}, 空格: {'spaces'}, 数字: {'digits'}, 其它字符: {'others'}\"\n",
    " \"\"\"\n",
    "    if question_number == 5:\n",
    "        content = f\"\"\"# 题目 {question_number}: {description}\n",
    "def solve():\n",
    "    def is_perfect(n):\n",
    "        divisors = [i for i in range(1, n) if n % i == 0]\n",
    "        return sum(divisors) == n\n",
    "    \n",
    "    perfect_numbers = [i for i in range(1, 1001) if is_perfect(i)]\n",
    "    return f\"1000以内的完数有: {'perfect_numbers'}\"\n",
    " \"\"\"\n",
    "    if question_number == 6:\n",
    "        content = f\"\"\"# 题目 {question_number}: {description}\n",
    "import math\n",
    "def solve():\n",
    "    N = int(input(\"请输入一个正整数N: \"))\n",
    "    factorial_sum = sum(math.factorial(i) for i in range(1, N + 1))\n",
    "    return f\"1+2!+3!+...+{'N'}! 的值是: {'factorial_sum'}\"\n",
    " \"\"\"\n",
    "    if question_number == 7:\n",
    "        content = f\"\"\"# 题目 {question_number}: {description}\n",
    "def solve():\n",
    "    numbers = list(map(int, input(\"请输入10个数（用空格分隔）: \").split()))\n",
    "    sorted_numbers = sorted(numbers)\n",
    "    return f\"排序后的数字是: {'sorted_numbers'}\"\n",
    " \"\"\"          \n",
    "    if question_number == 8:\n",
    "        content = f\"\"\"# 题目 {question_number}: {description}\n",
    "def solve():\n",
    "    sorted_array = list(map(int, input(\"请输入已排序数组的元素（用空格分隔）: \").split()))\n",
    "    new_element = int(input(\"请输入要插入的新元素: \"))\n",
    "    \n",
    "    # 找到插入位置\n",
    "    for i in range(len(sorted_array)):\n",
    "        if sorted_array[i] > new_element:\n",
    "            sorted_array.insert(i, new_element)\n",
    "            break\n",
    "    else:\n",
    "        sorted_array.append(new_element)\n",
    "    \n",
    "    return f\"插入新元素后的数组是: {'sorted_array'}\"\n",
    " \"\"\"\n",
    "    if question_number == 9:\n",
    "        content = f\"\"\"# 题目 {question_number}: {description}\n",
    "def solve():\n",
    "    n = int(input(\"请输入总人数n: \"))\n",
    "    position = int(input(\"请输入报数的位置（例如3表示报到3的人退出）: \"))\n",
    "    \n",
    "    people = list(range(1, n + 1))\n",
    "    index = 0\n",
    "    \n",
    "    while len(people) > 1:\n",
    "        index = (index + position - 1) % len(people)\n",
    "        people.pop(index)\n",
    "    \n",
    "    return f\"最后留下的是原来第 {'people'[0]} 号的那位\"\n",
    " \"\"\"      \n",
    "    else:\n",
    "        # 默认情况：创建一个带有占位solve函数的文件\n",
    "        content = f\"# 题目 {question_number}: {description}\\n\\ndef solve():\\n    pass\\n\"\n",
    "    with open(file_path, 'w') as f:\n",
    "        f.write(content)\n",
    "# 动态导入并执行题目函数\n",
    "def run_question(question_number):\n",
    "    desc = question_bank.get(question_number)\n",
    "    if desc is None:\n",
    "        print(\"题目编号不存在\")\n",
    "        return\n",
    "    file_path = os.path.join(QUESTION_DIR, f\"question_{question_number}.py\")\n",
    "    if not os.path.exists(file_path):\n",
    "        print(f\"警告：题目文件 {file_path} 不存在，正在生成...\")\n",
    "        generate_solve_file(question_number, desc)\n",
    "        if not os.path.exists(file_path):\n",
    "            print(f\"错误：无法生成题目文件 {file_path}。\")\n",
    "            return\n",
    "    try:\n",
    "        spec = importlib.util.spec_from_file_location(f\"question_{question_number}\", file_path)\n",
    "        module = importlib.util.module_from_spec(spec)\n",
    "        sys.modules[f\"question_{question_number}\"] = module\n",
    "        spec.loader.exec_module(module)\n",
    "        if hasattr(module, 'solve'):\n",
    "            result = module.solve()\n",
    "            print(result)\n",
    "        else:\n",
    "            print(\"题目文件中没有定义solve函数\")\n",
    "    except Exception as e:\n",
    "        print(f\"执行题目时发生错误: {e}\")\n",
    "# 菜单函数\n",
    "def show_menu():\n",
    "    print(\"题库管理系统\")\n",
    "    print(\"1. 查看题目索引\")\n",
    "    print(\"2. 运行题目\")\n",
    "    print(\"3. 增加题目\")\n",
    "    print(\"4. 使用 subprocess 执行外部程序\")\n",
    "    print(\"5. 退出\")\n",
    "\n",
    "def main():\n",
    "    init_question_files()\n",
    "    \n",
    "    while True:\n",
    "        show_menu()\n",
    "        choice = input(\"请选择操作: \")\n",
    "        \n",
    "        if choice == '1':\n",
    "            print(\"题目索引:\")\n",
    "            for idx, desc in question_bank.items():\n",
    "                print(f\"{idx}. {desc}\")\n",
    "        elif choice == '2':\n",
    "            question_number = input(\"请输入题目编号: \")\n",
    "            if question_number.isdigit() and int(question_number) in question_bank:\n",
    "                run_question(int(question_number))\n",
    "            else:\n",
    "                print(\"题目编号不存在或输入无效\")\n",
    "        elif choice == '3':\n",
    "            question_number = input(\"请输入新的题目编号: \")\n",
    "            if question_number.isdigit():  # 确保输入的是数字\n",
    "                question_desc = input(\"请输入题目描述: \")\n",
    "                question_bank[int(question_number)] = question_desc\n",
    "                generate_solve_file(int(question_number), question_desc)\n",
    "                print(\"题目添加成功\")\n",
    "            else:\n",
    "                print(\"题目编号必须是数字\")\n",
    "        elif choice == '4':\n",
    "            cmd = input(\"请输入要执行的命令（例如: ls -l, 注意：仅允许执行安全命令）: \")\n",
    "            # 这里可以添加更多的命令验证逻辑，例如只允许执行白名单命令\n",
    "            if not cmd.strip():  # 避免执行空命令\n",
    "                print(\"命令不能为空\")\n",
    "            else:\n",
    "                try:\n",
    "                    p = subprocess.Popen(cmd.split(), text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n",
    "                    out, err = p.communicate()\n",
    "                    print(\"Output:\", out)\n",
    "                    if err:\n",
    "                        print(\"Error:\", err)\n",
    "                except Exception as e:\n",
    "                    print(f\"执行命令时发生错误: {e}\")\n",
    "        elif choice == '5':\n",
    "            break\n",
    "        else:\n",
    "            print(f\"错误：无效的选择 {choice}。请重新选择。\")\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
